package cn.itcast.web.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的异常处理器
 *   1、实现HandlerExceptionResolver
 *   2、交给容器管理
 */
@Component
public class SaaSExceptionHandler implements HandlerExceptionResolver {

	/**
	 *  异常处理器方法
	 *      返回值：ModelAndView（跳转页面，携带错误信息）
	 *      参数： Exception 当前抛出的异常
	 */
	public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
		//当出现的异常时权限不足异常时：UnauthorizedException跳转到权限不足页面
		if(e instanceof UnauthorizedException) {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("forward:/unauthorized.jsp");
			return mv;
		}else{
			//如果是其他异常，按照之前的代码执行
			e.printStackTrace();
			ModelAndView mv = new ModelAndView();
			mv.addObject("errorMsg","对不起，我错了");
			mv.setViewName("error");
			return mv;
		}
	}
}
